from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect, HttpRequest
from django.shortcuts import render
from django.http import JsonResponse
from user.models import User
from .models import Note, Like
from django.views.generic import CreateView
from .forms import ArticleForm



# Create your views here.

def check_session_cookies(request):
    username=request.session.get('username')
    if not username:
        username=request.COOKIES.get('username')
        if not username:
            return False
        is_exist=User.objects.filter(username=username)
        if is_exist:
            request.session['username']=username
            request.session['uid'] = request.COOKIES.get('uid')
            return True
        else:
            return False
    else:
        is_exist = User.objects.filter(username=username)
        if is_exist:
            return True
        else:
            username = request.COOKIES.get('username')
            if not username:
                return False
            is_exist = User.objects.filter(username=username)
            if is_exist:
                request.session['username'] = username
                request.session['uid'] = request.COOKIES.get('uid')
                return True
            else:
                return False

def check_login(fn):
    def wrap(request, *args,**kwargs):
        if check_session_cookies(request):
            return fn(request, *args, **kwargs)
        else:
            return HttpResponseRedirect('/user/login')
    return wrap


@check_login
def add_view(request: HttpRequest):
    if request.method == 'GET':
        form = ArticleForm()
        return render(request, 'note/add_note.html', {'form': form})
    elif request.method == 'POST':
        print(request.POST)
        username = request.session['username']
        title = request.POST['title']
        content = request.POST['content']
        tag1 = request.POST['tag1']
        tag2 = request.POST['tag2']
        try:
            user = User.objects.get(username=username)
            # Note.objects.create(title=title, content=content, auther=user)
            note = Note(title=title, content=content, auther=user, tag1=tag1, tag2=tag2)
            if 'is_show' not in request.POST:
                note.is_show = False
            else:
                note.is_show = True
            note.save()
        except Exception as e:
            print("add failed %s" % (e))
            return HttpResponse("添加失败 %s" % (e))

        return HttpResponseRedirect('/note/mynote')


@check_login
def update_view(request):
    if request.method == "GET":
        return render(request, 'note/update_note.html')
    elif request.method == "POST":
        return HttpResponse("修改成功")


@check_login
def delete_view(request: HttpRequest):
    auther = request.GET['auther']
    noteId = request.GET['noteId']
    try:
        note = Note.objects.get(id=noteId)
        note.delete()
        print(note)
    except:
        print("删除失败！！！")
    return HttpResponseRedirect('/note/mynote')

@check_login
def notelist_view(request):
    notelist = Note.objects.all()
    # print(locals())
    return render(request, 'note/notelist.html', locals())

@check_login
def get_note_of(request):
    name = request.session.get("username")
    user = User.objects.filter(username=name)
    notelist = Note.objects.filter(auther_id=name)
    return render(request, 'note/ones_note.html', locals())

@check_login
def get_note_single(request: HttpRequest):
    username = request.session.get("username")
    user = User.objects.filter(username=username)
    targetUser = request.GET['auther']
    targetID = request.GET['noteId']
    note = Note.objects.filter(id=targetID)
    records = Like.objects.filter(user=username, note=targetID)
    if records:
        like = True
    else:
        like = False

    for n in note:
        n.seen_num += 1
        n.save()
    if username == targetUser:
        flag = True
    else:
        flag = False
    dic = {};
    dic['username'] = username
    dic['targetUser'] = targetUser
    dic['note'] = note[0]
    dic['flag'] = flag
    dic['like'] = like
    dic['sorted_tag_key'] = tag_count().keys()
    dic['sorted_tag_value'] = tag_count().values()

    return render(request, 'note/single_note.html', dic)


def getNoteByTag(tag):
    lis=[]
    all_note = Note.objects.all()
    for note in all_note:
        if tag in [note.tag1,note.tag2]:
            lis.append(note)
    return lis

def tag_count():
    dict={}
    all_note=Note.objects.all()
    for note in all_note:
        if note.tag1!="":
            if note.tag1 not in dict.keys():
                dict[note.tag1]=0
            dict[note.tag1]+=1
        if note.tag2!="":
            if note.tag2 not in dict.keys():
                dict[note.tag2]=0
            dict[note.tag2]+=1
    return {k: v for k, v in sorted(dict.items(), key=lambda item: item[1], reverse=True)}


@check_login
def note_edit(request: HttpRequest):
    if request.method == 'GET':
        auther = request.GET['auther']
        noteId = request.GET['noteId']
        note = Note.objects.filter(id=noteId)[0]
        data = {}
        data['title'] = note.title
        data['tag1'] = note.tag1
        data['tag2'] = note.tag2
        data['content'] = note.content
        if note.is_show:
            data['is_show'] = True
        form = ArticleForm(data)
        dic = {}
        dic['note'] = note
        dic['auther'] = auther
        dic['form'] = form
        return render(request, 'note/edit_note.html', dic)

    elif request.method == 'POST':
        noteId = request.GET['noteId']
        note = Note.objects.filter(id=noteId)[0]
        note.title = request.POST['title']
        note.tag1 = request.POST['tag1']
        note.tag2 = request.POST['tag2']
        note.content = request.POST['content']
        print(request.POST)
        if 'is_show' not in request.POST:
            note.is_show = False
        else:
            note.is_show = True
        note.save()
        return HttpResponseRedirect('/note/mynote')

@check_login
def like_handle(request: HttpRequest):
    def success_response(like_num, like):
        data = {}
        data['status'] = 'SUCCESS'
        data['like_num'] = like_num
        data['like'] = like
        return JsonResponse(data)

    def error_response(message):
        data = {}
        data['status'] = 'ERROR'
        data['message'] = message
        return JsonResponse(data)

    username = request.POST['user']
    targetNote = request.POST['targetNote']
    print(request.POST)
    print(username)
    print(targetNote)
    user = User.objects.filter(username=username)[0]
    targetNote = Note.objects.filter(id=targetNote)[0]
    like_record, created = Like.objects.get_or_create(user=user, note=targetNote)
    print(created)

    if created:
        #没有点赞过
        like_record.save()
        targetNote.ok_num = targetNote.ok_num + 1
        targetNote.save()
        like = True
        return success_response(targetNote.ok_num, like)
    else:
        like = False
        like_record.delete()
        targetNote.ok_num = targetNote.ok_num - 1
        targetNote.save()
        return success_response(targetNote.ok_num, like)


@check_login
def search_handle(request: HttpRequest):
    if request.method == 'POST':
        search_content = request.POST['search_content']
        notelist = Note.objects.filter(Q(title__contains=search_content))
        return render(request, "note/note_search.html", locals())
    elif request.method == 'GET':
        tag = request.GET['tag']
        notelist = getNoteByTag(tag)
        return render(request, "note/note_search.html", locals())



# @check_login
# def myadd(request: HttpRequest):
#     if request.method == 'GET':
#         form = ArticleForm()
#         return render(request, 'note/add_note.html', {'form': form})
#     elif request.method == 'POST':
#         print(request.POST)
#         username = request.session['username']
#         title = request.POST['title']
#         content = request.POST['content']
#         tag1 = request.POST['tag1']
#         tag2 = request.POST['tag2']
#         try:
#             user = User.objects.get(username=username)
#             # Note.objects.create(title=title, content=content, auther=user)
#             note = Note(title=title, content=content, auther=user, tag1=tag1, tag2=tag2)
#             if 'is_show' not in request.POST:
#                 note.is_show = False
#             else:
#                 note.is_show = True
#             note.save()
#         except Exception as e:
#             print("add failed %s" % (e))
#             return HttpResponse("添加失败 %s" % (e))
#
#         return HttpResponseRedirect('/note/mynote')